//
//  CurriculumAllEvaVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/7/20.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "CurriculumAllEvaVC.h"
#import "ZYCourseAttendanceTowModel.h"
#import "CurriculumAllEvaCell.h"
#import "HNThreeGoodEvaDetailVC.h"

@interface CurriculumAllEvaVC ()<UITableViewDelegate,UITableViewDataSource>
{
    IBOutlet UITableView *_TableView;
    
    // 全选按钮
    IBOutlet UIButton *_AllSelectBtn;
}
/** 数据 */
@property (nonatomic, strong) NSMutableArray <ZYCourseAttendanceTowModel *>*DataArr;

@property(nonatomic,strong) NSMutableArray *selectArray;//(通过比较判断这个数组来确定全选按钮能不能被点击)
/**
 是否被全选
 */
@property (nonatomic, assign) BOOL AllSelect;
@end

@implementation CurriculumAllEvaVC

// 清空下选择
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (self.DataArr.count > 0)
    {
        _AllSelectBtn.selected = YES;
        [self ClickAllSelect:_AllSelectBtn];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"三好评价";

    [_TableView registerNib:[UINib nibWithNibName:[CurriculumAllEvaCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];

    [self RefreshData];
}

#pragma mark - 网络请求
/**
 本页数据请求
 */
- (void)RefreshData
{
    
    ///yxhUser.do
    
    
    [HUD showHUD];
    NSMutableDictionary *Dict = [NSMutableDictionary dictionary];
    [Dict setValue:self.ID forKey:@"lessonId"];
    [Dict setValue:self.IsTeacher ? @"getCourseCommentStudent":@"getCourseRecord" forKey:@"action"];
    [Dict setValue:@1 forKey:@"pageNumber"];
    NSString *url;
    NSLog(@"%d",self.IsTeacher);
    if (self.IsTeacher) {
      //  http://192.168.0.226:8080/StarShine/ys/yxhUser.do&action=getCourseCommentStudent&lessonId=814&pageNumber=1
        url = [NSString stringWithFormat:@"yxhUser.do?action=getCourseCommentStudent&lessonId=%@&pageNumber=1",[self.ID stringValue]];
    } else {
        //   http://192.168.0.226:8080/StarShine/ys/yxhUser.do&action=getCourseRecord&lessonId=814&oid=1
        url = [NSString stringWithFormat:@"yxhUser.do?action=getCourseRecord5&lessonId=%@&oid=%@",[self.ID stringValue],[AccountTool shareAccountTool].currentAccount.oid];
    }

    
    
    
    
    NSLog(@"%@  %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {

        [HUD hideHUD];
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 取模型
            NSArray *Arr = Obj[@"t"][@"dataList"];
            // 转对象
            [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                ZYCourseAttendanceTowModel *Model = [[ZYCourseAttendanceTowModel alloc] init_ObjectForValue:obj];
                //通过比较判断这个数组来确定全选按钮能不能被点击
                if ([Model.commentCount integerValue] >= [Model.courseCount integerValue]) {
                    
                }else {
                    [self.selectArray addObject:Model];
                }
                if (self.selectArray.count > 0) {//有能签到的数据
                    _AllSelectBtn.userInteractionEnabled = YES;
                }else {
                    _AllSelectBtn.userInteractionEnabled = NO;
                }
                
                Model.isSign = @1;
                // 转对象并保存下来
                [self.DataArr addObject:Model];
            }];
            [_TableView reloadData];
        }
        else
        {
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [HUD hideHUD];
        [HUD showError:NetErr];
    }];
}



#pragma mark - 点击事件
/**
 单击了全选
 */
- (IBAction)ClickAllSelect:(UIButton *)sender
{
    [self MgrAllSelect:sender];
}

/**
 点击了确认
 */
- (IBAction)ClickSure:(UIButton *)sender
{
    self.Sure ();
}

#pragma mark - 处理事件
/**
 处理全选事件
 */
- (void)MgrAllSelect:(UIButton *)Button
{
    // 状态互反
    Button.selected = !Button.selected;

    [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 不能选中未完成的
        if ([obj.type isEqualToNumber:@0]) {
        obj.isSign = Button.selected?@2:@1;
        }
    }];
    [_TableView reloadData];
}

/**
 处理选择事件
 */
- (instancetype (^)(ZYCourseAttendanceTowModel *,UIButton *))MgrSelect {

    return  ^(ZYCourseAttendanceTowModel *Model,UIButton *Button) {

        
        
        Button.selected = !Button.selected;
        
        // 这个Model是未完成的话，剩余的全部按钮都必须禁止点击
        if (![Model.type isEqualToNumber:@0]) {
            [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.Enable = NO;
            }];
            Model.Enable = YES;
            [_TableView reloadData];
        } else {
            // 这个点击并不是未完成的话就将所有未完成的禁用
            [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.Enable = [obj.type isEqualToNumber:@0] ? YES:NO;
            }];
            [_TableView reloadData];
        }
        Model.isSign = Button.selected?@2:@1;
        // 判断是否全选
        [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 不能选中未完成的
            if ([obj.type isEqualToNumber:@0]) {
            _AllSelect = [obj.isSign isEqualToNumber:@2] ? YES:NO;
            *stop = !_AllSelect;
            }
        }];
        _AllSelectBtn.selected = _AllSelect;
        return self;
    };
}
/**
 实现提交方法
 */
- (instancetype (^)())Sure {

    return ^() {

        //临时保存已中状态的对的模型ID
        NSMutableArray *IDArr = [NSMutableArray array];
        NSMutableArray *EnrollInfoIdArr = [NSMutableArray array];
        __block ZYCourseAttendanceTowModel *TempMpdel = nil;
        //挑选ID
        [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            ZYCourseAttendanceTowModel *Model = obj;
            //符合就加入豪华晚餐
            [Model.isSign isEqualToNumber:@2]?[IDArr addObject:[Model.user_ID stringValue]]:nil;
            [Model.isSign isEqualToNumber:@2]?[EnrollInfoIdArr addObject:[Model.enrollInfoId stringValue]]:nil;
            [Model.type isEqualToNumber:@1] && [Model.isSign isEqualToNumber:@2] ?TempMpdel = Model:nil;
        }];

        //判断是否能评价
        if (self.DataArr.count > 0 && IDArr.count == 0) {

            [HUD showError:@"未选择需要评价的学生"];
        } else if (self.DataArr.count == 0) {

            [HUD showError:@"该课程暂无学员"];
        } else {

            //得到最终IDArr后转成字符串
            // 打开评价
            NSString *IDStr = [IDArr componentsJoinedByString:@","];
            NSString *EnrollInfoIdStr = [EnrollInfoIdArr componentsJoinedByString:@","];
            __block HNThreeGoodEvaDetailVC *VC = [[HNThreeGoodEvaDetailVC alloc] init];
            VC.ID = self.ID;
            VC.Uids = IDStr;
            if ([IDStr componentsSeparatedByString:@","].count == 1 && TempMpdel && ![TempMpdel.type isEqualToNumber:@0]) {
                VC.TempID = TempMpdel.tempId;
            }
            VC.EnrollInfoIds = EnrollInfoIdStr;
            
            //  取单个信息
            if ([[EnrollInfoIdStr componentsSeparatedByString:@","] count] == 1) {
                
                [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if ([EnrollInfoIdStr isEqualToString:[obj.enrollInfoId stringValue]]) {
                        VC.Name = obj.user_petName ? [NSString stringWithFormat:@"%@",obj.user_petName]:[NSString stringWithFormat:@"%@",obj.user_username];
                        VC.LessonName = self.Name;
                        VC.ImgStr = obj.avatar;
                    }
                }];
            }
            VC.PoP = ^{
                [self.DataArr removeAllObjects];
                [_TableView reloadData];
                [self RefreshData];
            };
            [self.navigationController pushViewController:VC animated:YES];
        }
        return self;
    };
}
#pragma mark - TableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取对象
    ZYCourseAttendanceTowModel *Model = self.DataArr[indexPath.row];
    // 实例化
    CurriculumAllEvaCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    // 点语法
    Cell.Model (Model);
    //单击了选择
    Cell.ClickSelect = ^(UIButton *Button){

        self.MgrSelect(Model,Button);
    };

    return Cell;
}

#pragma mark - Setter
- (NSMutableArray<ZYCourseAttendanceTowModel *> *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

-(NSMutableArray *)selectArray {
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

@end
